package com.co.ud.icehome;

import java.io.Serializable;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import javax.annotation.PostConstruct;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.SessionScoped;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import javax.portlet.PortletContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;

import org.apache.log4j.Logger;
import org.icefaces.application.PortableRenderer;
import org.icefaces.application.PushRenderer;

import com.co.ud.icehome.connector.ClientMessageListener;
import com.co.ud.icehome.connector.RequestConnectorActiveMQ;
import com.co.ud.icehome.sensores.LightSensor;
import com.co.ud.icehome.utils.enums.ProtocolIceHome;
import com.co.ud.icehome.utils.patterns.observer.Subject;

/*
 * Job Applicant model
 */
@ManagedBean(name = "panelSensorico")
@SessionScoped
public class PanelSensorico implements Observer, Serializable {

	private String messageGroup = "" + 0;
	private String userId = "" + 0;
	private Subject subject = new Subject();
	private PortableRenderer m_renderer;
	private String m_sessionId;
	private Logger logger = Logger.getLogger(this.getClass());

	public PanelSensorico() {

		System.out.println("creando Panel sensorico");
		// /////////////////////////////////////////////////////////////////
		// ////////////////////////////user/////////////////////////////////
		// /////////////////////////////////////////////////////////////////
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		PortletSession portletSession = (PortletSession) externalContext
				.getSession(false);
		PortletContext portletContext = portletSession.getPortletContext();
		logger.info("portletcontext = " + portletContext);

		logger.info("portletRequest = "
				+ externalContext.getRequest().getClass().getName());

		RenderRequest renderRequest = (RenderRequest) externalContext
				.getRequest();

		logger.info("RenderRequest = " + renderRequest);

		Map userInfo = (Map) renderRequest
				.getAttribute(PortletRequest.USER_INFO);
		logger.info("userinfo = " + userInfo);
		this.userId = (String) userInfo.get("liferay.user.id");
		logger.info("userinfo = " + userId);

		// /asignacion de grupo de mensajeria
		messageGroup = userId;
		logger.info("messageGroup = " + messageGroup);

		// /////////////////////////////////////////////////////////////////
		// ///////////////////////////pattern
		// observer/////////////////////////////////
		// /////////////////////////////////////////////////////////////////
		ClientMessageListener clientMessageListener = new ClientMessageListener(
				this);

		System.out.println("Panel sensorico creado exitosamente");
		
		int consumer_id= 10095;
		for (int i = 0; i < 100; i++) {
			
			IceHomeConsumersFactory consumersFactory = new IceHomeConsumersFactory(consumer_id);
			consumer_id++;
		}

	}

	@PostConstruct
	public void postConstruct() {

		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		PortletSession portletSession = (PortletSession) externalContext
				.getSession(false);

		// /////////////////////////////////////////////////////////////////
		// ///////////////////////////render portable///////////////////////
		// /////////////////////////////////////////////////////////////////

		logger.info("portletsession = " + portletSession);
		this.m_sessionId = portletSession.getId();
		PushRenderer.addCurrentSession(this.m_sessionId);
		this.m_renderer = PushRenderer.getPortableRenderer();
		//new BidThread().start();
		// m_renderer.render(m_sessionId);
	}

	public Subject getSubject() {
		return subject;
	}

	public void setSubject(Subject subject) {
		this.subject = subject;
	}

	public PortableRenderer getM_renderer() {
		return m_renderer;
	}

	public void setM_renderer(PortableRenderer m_renderer) {
		this.m_renderer = m_renderer;
	}

	public String getM_sessionId() {
		return m_sessionId;
	}

	public void setM_sessionId(String m_sessionId) {
		this.m_sessionId = m_sessionId;
	}

	public String getMessageGroup() {
		return messageGroup;
	}

	public void setMessageGroup(String messageGroup) {
		this.messageGroup = messageGroup;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		// TODO Auto-generated method stub
		System.out.println("-->> Mensaje desde observable: " + arg1);
		this.subject = (Subject) arg1;
	   
		
		System.out.println("-->>subject state : "
				+ this.subject.getTemperatura());

		// PushRenderer.render(PUSH_GROUP);
		// this.setTemperatura(this.subject.getTemperatura());
		m_renderer.render(m_sessionId);
		// txtTemperatura.setValue(subject.getTemperatura());
		System.out.println("-->> observable is Update!!!!: ");

	}

/*	private class BidThread extends Thread {
		public void run() {
			for (int i = 0; i < 2; i++) {
				try {
					sleep(2000);
					System.out.println("Score has changed");
					m_renderer.render(m_sessionId);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
*/
	public void bajarIntensidad(ActionEvent e) {

		logger.info("Metodo-bajar intensidad");

		RequestConnectorActiveMQ requestConnectorActiveMQ = RequestConnectorActiveMQ
				.getInstance();

		logger.info("MetodoAsignando valores de envio");
		LightSensor lightSensor = new LightSensor();
		
		Integer intensidad= (Integer.parseInt(this.subject.getControlLuminico())-1);
		this.subject.setControlLuminico(intensidad.toString());
		
		//fix scale
		int sensorValue=Integer.valueOf(this.subject.getControlLuminico())*2;
		lightSensor.setData_sensor(""+sensorValue);
		//send message
		logger.info("Enviando.....");

		requestConnectorActiveMQ.sendMessage(ProtocolIceHome.SendMessage(
				userId, lightSensor));
		m_renderer.render(m_sessionId);

		logger.info("Mensaje enviado");
		

		
		
	//	this.subject.setTemperatura("0");
	//	m_renderer.render(m_sessionId);
	}

	public void subirIntensidad(ActionEvent e) {

		logger.info("Metodo-subir intensidad");

		RequestConnectorActiveMQ requestConnectorActiveMQ = RequestConnectorActiveMQ
				.getInstance();

		logger.info("MetodoAsignando valores de envio");
		LightSensor lightSensor = new LightSensor();
		
		Integer intensidad= (Integer.parseInt(this.subject.getControlLuminico())+1);
		this.subject.setControlLuminico(intensidad.toString());
		// fix scale
		int sensorValue=Integer.valueOf(this.subject.getControlLuminico())*2;
		lightSensor.setData_sensor(""+sensorValue);
		//send message
		logger.info("Enviando.....");
		requestConnectorActiveMQ.sendMessage(ProtocolIceHome.SendMessage(
				userId, lightSensor));
		m_renderer.render(m_sessionId);

		logger.info("Mensaje enviado");

	}

}
